package com.patterns.connection;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import com.patterns.Cache;

public class ClientConnection extends NetworkConnection implements Runnable{
	
	private Socket requestSocket;
	private volatile Cache cache;
	
	public ClientConnection(String server,int port) throws UnknownHostException, IOException {
		super(port);
		requestSocket = new Socket(server,port);
		myThread = new Thread(this);
        myThread.start();
	}
	
	public ClientConnection(String server) throws UnknownHostException, IOException{
		this(server,DEFAULT_PORT);
	}

	@Override
	public void run() {
		while(!Thread.currentThread().isInterrupted()){
            InputStream in;
            try {
                    in = requestSocket.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(in);
                    ObjectInputStream ois = new ObjectInputStream(bis);
                    cache = (Cache) ois.readObject();
                    System.out.println(cache);
            } catch (SocketException e){
            	
            } catch (IOException | ClassNotFoundException e){
                    e.printStackTrace();
            }
		}
	}

	public void shutDown(){
		try {
			requestSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		super.shutDown();
	}

	public Cache getCache(){
		return cache;
	}

}
